/*
 * -------------------------------------------------------------------------
 * 小工具
 * -------------------------------------------------------------------------
 */

/**
 * 补0
 * @param num
 * @returns {string|*}
 */
const fillZero = num => (num < 10) ? `0${num}` : num;

/**
 * 获取日期
 * @returns String
 */
const getYmd = () => {
    let time = new Date();
    return `${time.getFullYear()}-${fillZero(time.getMonth() + 1)}-${fillZero(time.getDate())}`;
};

/**
 * 获取完整时间
 * @param timestamp
 * @returns {`${number}-${*}-${*} ${*}:${*}:${*}`}
 */
const getFullTime = timestamp => {
    let t = timestamp ? (new Date(timestamp * 1000)) : (new Date());
    let Y = t.getFullYear();
    let m = t.getMonth() + 1;
    let d = t.getDate();
    let H = t.getHours();
    let i = t.getMinutes();
    let s = t.getSeconds();
    
    /*拼装格式 Y-m-d H:i:s*/
    return `${Y}-${fillZero(m)}-${fillZero(d)} ${fillZero(H)}:${fillZero(i)}:${fillZero(s)}`;
};

/**
 * 字节转换
 * @param bytes
 * @return {string}
 */
const bytesSize = (bytes, blank) => {
    bytes = bytes || 0;
    blank = blank || '';
    if (bytes === 0) return `0${blank}B`;
    
    let k     = 1024;
    let sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    let i     = Math.floor(Math.log(bytes) / Math.log(k));
    let num   = bytes / Math.pow(k, i);
    
    return `${num.toPrecision(3)}${blank}${sizes[i]}`;
};

/**
 * 转换为数字
 * @param num
 * @returns {number|number}
 */
const toInt = num => {
    let n = parseInt(num, 10);
    return isNaN(n) ? 0 : n;
};

/**
 * 转驼峰命名
 * @param str 字符串
 * @param firstUpper 首字母大写
 * @param split 分隔符
 * @return {*}
 */
const toHump = (str, firstUpper, split) => {
    split      = split || '_';
    const hump = str.toString().replace(new RegExp(`\\${split}(\\w)`, 'g'), ($0, $1) => $1.toUpperCase());
    
    /*首字母大写*/
    if (firstUpper === true) return `${hump.charAt(0).toUpperCase()}${hump.slice(1)}`;
    
    /*首字母小写*/
    return hump;
};

/**
 * 创建uuid
 * @return {string}
 */
const uuidGenerate = () => {
    let d    = new Date().getTime();
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = (d + Math.random() * 16) % 16 | 0;
        d     = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x7) | 0x8).toString(16);
    });
    return uuid;
};

/**
 * 导出
 * @type {{getYmd: (function(): string), getFullTime: (function(*): string), toInt: (function(*=): number|number), uuidGenerate: (function(): string), bytesSize: ((function(*=, *=): string)|*), fillZero: (function(*): string|*), toHump: ((function(*, *, *=): *)|*)}}
 */
module.exports = {
    fillZero,
    getYmd,
    bytesSize,
    getFullTime,
    toInt,
    toHump,
    uuidGenerate
};
